package com.roc.web.action.settlemgr;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.roc.bean.TblMgmRiskBack;
import com.roc.bean.TblMgmRiskBackLog;
import com.roc.page.BaseSearchCondition;
import com.roc.page.PaginationBaseAction;
import com.roc.pojo.Operators;
import com.roc.pojo.WindControllSta;
import com.roc.service.IExcelService;
import com.roc.service.IPagenitionService;
import com.roc.service.MarginAndReturnService;
import com.roc.service.ServiceException;
import com.roc.util.Constance;
import com.roc.util.constant.Constant;
import com.roc.util.constant.Role;

/**
 * 保证金及退货控制
 * @author Administrator
 *
 */
@Component
@Namespace("/margin")
@Scope("prototype")
public class MarginAndReturnAction extends PaginationBaseAction{
	
	private static Logger logger = Logger.getLogger(MarginAndReturnAction.class);
	
	private MarginAndReturnSearchCondition searchCondition;
	
	private TblMgmRiskBack riskBack;
	
	private String mchtCd;
	
	private String securityAmt;
	
	private String details;
	
	@Autowired
	private IPagenitionService pagenitionService;
	
	@Autowired
	private MarginAndReturnService marginAndReturnService;
	
	@Autowired
	IExcelService excelService;
	
	private InputStream excelFile;
	
	/**
	 * 初始保证金页面
	 * 
	 * @return
	 * @throws Exception
	 */
	@Action(value = "init", results = {
			@Result(name = "success", location = "/pages/settlement/marginAndReturn.jsp"),
			@Result(name = "error", location = "/error.jsp") })
	public String init() throws Exception {
		Operators op = (Operators) getSession().getAttribute(
				Constant.SESSION_LOGIN_MERCHANT);
		if (op.getRoleType().equals(Role.CLEAR_OPERATORS.getCode())
				|| op.getRoleType().equals(Role.CLEAR_LEAD.getCode())
				|| op.getRoleType().equals(Role.SYSTEM.getCode())
				|| op.getRoleType().equals(Role.RISK_CONTROL_LEAD.getCode())
				|| op.getRoleType().equals(
						Role.RISK_CONTROL_OPERATORS.getCode())) {
			return SUCCESS;
		}
		addActionError("无权限访问!!!");
		return ERROR;
	}
	
	/**
	 * 查询保证金页面
	 * 
	 * @return
	 * @throws Exception
	 */
	@Action(value = "queryMargin", results = {
			@Result(name = "success", location = "/pages/settlement/marginAndReturn.jsp"),
			@Result(name = "error", location = "/error.jsp") })
	public String queryMargin() throws Exception {
		try {
			
			if (searchCondition == null) {
				searchCondition = (MarginAndReturnSearchCondition) getSearchConditionFromSession();
				if (searchCondition == null) {
					searchCondition = new MarginAndReturnSearchCondition();
				}
			}
			int rows = pagenitionService.countSQL(searchCondition);

			if (rows > 0) {
				searchRsList = pagenitionService.findAllSQL(searchCondition,calcuStart(getCurrentPage()), Constance.PAGE_MAX_SIZE);
			}
			
			List<TblMgmRiskBack> riskList = new ArrayList<TblMgmRiskBack>();
			dealTheListSpecially(searchRsList,riskList);

			

			this.setTotalPage(this.calcuTotalPage(rows));
			getRequest().setAttribute(SEARCH_RS_LIST, riskList);
			getRequest().setAttribute(CURRENT_PAGE, this.getCurrentPage());
			getRequest().setAttribute(TOTAOL_PAGE, this.getTotalPage());
			setSearchToConditionSession(searchCondition);
			
			
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			addActionError(e.getMessage());
			return ERROR;
		}
		return SUCCESS;

	}
	
	/**
	 * 添加保证金页面
	 * 
	 * @return
	 * @throws Exception
	 */
	@Action(value = "addMargin", results = {
			@Result(name = "success", location = "/pages/settlement/addMargin.jsp"),
			@Result(name = "error", location = "/error.jsp") })
	public String addMargin() throws Exception {
		return SUCCESS;
	}
	
	/**
	 * 添加保证金操作
	 * 
	 * @return
	 * @throws Exception
	 */
	@Action(value = "addMarginSubmit", results = {
			@Result(name = "success", location = "/pages/settlement/addMargin.jsp"),
			@Result(name = "error", location = "/error.jsp") })
	public String addMarginSubmit() throws Exception {
		Operators op = (Operators) getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		try {
			Map<String,Object> res = marginAndReturnService.addMargin(op, riskBack);
			if(res == null){
				res= new HashMap<String, Object>();
				res.put("flag", false);
				res.put("msg", "操作失败");
			}
			getRequest().setAttribute("res", res);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			addActionError("添加保证金操作异常");
		}
		return SUCCESS;
	}
	
	/**
	 * 修改保证金
	 * @return
	 * @throws Exception
	 */
	@Action(value = "updateMarginSubmit")
	public String updateMarginSubmit(){
		Operators logingMerchant=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		HttpServletResponse response = ServletActionContext.getResponse();
	    response.setCharacterEncoding("UTF-8");
		JSONObject jsonObject = new JSONObject();
		PrintWriter out = null;
		Map<String,Object> resMap = null;
		try {
			out = response.getWriter();
			resMap = marginAndReturnService.updateMargin(logingMerchant, Constance.Null2EmptyTrim(mchtCd), Constance.Null2EmptyTrim(securityAmt));
			jsonObject.put("res", resMap);
			
		} catch (Exception e) {
			logger.error("修改退货保证金异常:{}",e);
			resMap = new HashMap<String, Object>();
			resMap.put("flag", false);
			resMap.put("msg", "修改退货保证金异常");
			jsonObject.put("res", resMap);
		}
		out.print(jsonObject.toString());
		out.flush();
		out.close();
		return null;
	}
	
	/**
	 * 查询退货金明细
	 * @Title: queryMarginAndReturnDetails
	 * @return
	 * @date: 2018年4月24日 
	 *
	 */
	@Action(value = "queryMarginAndReturnDetails", results = {
			@Result(name = "success", location = "/pages/settlement/marginDetails.jsp"),
			@Result(name = "error", location = "/error.jsp") })
	public String queryMarginAndReturnDetails(){
		List<Object> params = new ArrayList<Object>();
		
		if(details == null){
			details = (String) getSession().getAttribute("details");
		}
		params.add(Constance.Null2EmptyTrim(details));
		try {
			
			int rows = marginAndReturnService.queryMarginDetailsCount(params);
			List<TblMgmRiskBackLog>  riskList = new ArrayList<TblMgmRiskBackLog>();
			if(rows>0){
				riskList = marginAndReturnService.queryMarginDetails(params, calcuStart(getCurrentPage()), Constance.PAGE_MAX_SIZE);
			}
			getRequest().setAttribute(SEARCH_RS_LIST, riskList);
			this.setTotalPage(this.calcuTotalPage(rows));
			getRequest().setAttribute(CURRENT_PAGE, this.getCurrentPage());
			getRequest().setAttribute(TOTAOL_PAGE, this.getTotalPage());
			getSession().setAttribute("details", details);
			addActionMessage("当前条件下统计到【"+rows+"】条记录");
			
		} catch (Exception e) {
			logger.error("查询退货保证金操作流水异常",e);
		}
		
		return SUCCESS;
	}
	/**
	 * 导出退货金明细
	 * @Title: exportMarginAndReturnDetails
	 * @return
	 * @throws Exception
	 * @date: 2018年4月24日 
	 *
	 */
	@Action(value = "exportMarginAndReturnDetails", results = {
			@Result(name = "success", type = "stream", params = {
					"contentType", "application/vnd.ms-excel", "inputName",
					"excelFile", "contentDisposition",
					"attachment;filename=${excelName}.xls", "bufferSize",
					"1024*3" }),
			@Result(name = "error", location = "/pages/windControllSta/blacklist.jsp") })
	public String exportMarginAndReturnDetails() throws Exception {
		List<Object> params = new ArrayList<Object>();
		if(details == null){
			details = (String) getSession().getAttribute("details");
		}
		params.add(Constance.Null2EmptyTrim(details));
		
		int rows = marginAndReturnService.queryMarginDetailsCount(params);
		List<TblMgmRiskBackLog>  riskList = new ArrayList<TblMgmRiskBackLog>();
		try {
		if(rows>0){
			riskList = marginAndReturnService.queryMarginDetails(params, 0, rows);
		}
		
		SXSSFWorkbook work=excelService.exportMarginAndReturnDetails(riskList);
		
		 ByteArrayOutputStream output = new ByteArrayOutputStream();  
	       work.write(output);  
	   
	        byte[] ba = output.toByteArray();  
	         excelFile = new ByteArrayInputStream(ba);  
	         output.flush();  
	         output.close();  
	}catch (ServiceException e) {
		e.printStackTrace();
		logger.error(e.getMessage(),e);
		addActionError(e.getMessage());
		
	}
	
	return SUCCESS;
	}
	
	
	
	
	
	
	
	
	
	
	
	
	
	private void dealTheListSpecially(List<Object> searchRsList, List<TblMgmRiskBack> riskList) {
		try {
		    
			if(searchRsList!=null&&searchRsList.size()>0){
				Iterator it=searchRsList.iterator();
				while (it.hasNext()) {
					Object[] obj = (Object[]) it.next();
					TblMgmRiskBack risk = new TblMgmRiskBack();
					risk.setInsIdCd(Constance.Null2EmptyTrim(obj[0]));
					risk.setMchntCd(Constance.Null2EmptyTrim(obj[1]));
					risk.setTermId(Constance.Null2EmptyTrim(obj[2]));
					risk.setSecurityAmt(Constance.Null2EmptyTrim(obj[3]));
					risk.setCurrentAmt(Constance.Null2EmptyTrim(obj[4]));
					risk.setBackAmt(Constance.Null2EmptyTrim(obj[5]));
					risk.setName(Constance.Null2EmptyTrim(obj[6]));
					riskList.add(risk);
				}
			}
			
			
		} catch (Exception e) {
			logger.error("保证金查询List解析异常",e);
			throw new RuntimeException("保证金查询List解析异常");
		}
		
	}

	@Override
	protected BaseSearchCondition getSearchConditionFromSubClass()
			throws Exception {
		return searchCondition;
	}

	@Override
	protected void setSearchConditionToSubClass(
			BaseSearchCondition searchCondition) throws Exception {
		this.setSearchConditionToSubClass(searchCondition);
		
	}

	@Override
	protected void setSearchToConditionSession(
			BaseSearchCondition searchCondition) {
		getSession().setAttribute(SEARCH_SESSION_MARGIN_RETURN, searchCondition);
		
	}

	@Override
	protected BaseSearchCondition getSearchConditionFromSession() {
		return (BaseSearchCondition) getSession().getAttribute(
				SEARCH_SESSION_MARGIN_RETURN);
	}

	@Override
	protected String getInitPageSize() {
		return Constance.PAGE_MAX_SIZE + "";
	}

	public MarginAndReturnSearchCondition getSearchCondition() {
		return searchCondition;
	}

	public void setSearchCondition(MarginAndReturnSearchCondition searchCondition) {
		this.searchCondition = searchCondition;
	}

	public TblMgmRiskBack getRiskBack() {
		return riskBack;
	}

	public void setRiskBack(TblMgmRiskBack riskBack) {
		this.riskBack = riskBack;
	}

	public String getMchtCd() {
		return mchtCd;
	}

	public void setMchtCd(String mchtCd) {
		this.mchtCd = mchtCd;
	}

	public String getSecurityAmt() {
		return securityAmt;
	}

	public void setSecurityAmt(String securityAmt) {
		this.securityAmt = securityAmt;
	}

	public String getDetails() {
		return details;
	}

	public void setDetails(String details) {
		this.details = details;
	}
	
	
	
	
	public InputStream getExcelFile() {
		return excelFile;
	}

	public void setExcelFile(InputStream excelFile) {
		this.excelFile = excelFile;
	}

	public String getExcelName() {
		String excelName="退货保证金明细"+Constance.formateDate();
		 
			try {
				excelName = new String(excelName.getBytes(),"ISO8859-1");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
				logger.info("生成excel名称失败了！");
			}
		 
		return  excelName;
		
	}
	
}
